/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: WithdrawCoinActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.WithdrawCoinPresenter;
import io.bhex.app.account.viewhandler.ChainTypeViewController;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.utils.VerifyUtil;
import io.bhex.app.view.InputView;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.PopWindow;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.app.view.StepView;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.ChainType;
import io.bhex.sdk.trade.bean.AddressCheckResponse;
import io.bhex.sdk.trade.bean.AddressListResponse;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.sdk.trade.bean.FeeBeanResponse;
import io.bhex.sdk.trade.bean.TwoVerifyBean;
import io.bhex.sdk.trade.bean.WithDrawRequstBean;
import io.bhex.sdk.trade.bean.WithDrawVerifyBean;

/**
 * ================================================
 * 描   述：提币
 * ================================================
 */

public class WithdrawCoinActivity extends BaseActivity<WithdrawCoinPresenter, WithdrawCoinPresenter.WithdrawCoinUI> implements WithdrawCoinPresenter.WithdrawCoinUI, View.OnClickListener, CompoundButton.OnCheckedChangeListener, StepView.StepViewProgressListener {
    private static final int REQUEST_CODE_SCAN = 0x008;
    private static final int REQUEST_CODE_ADDRESS = 0x009;
    private static final int REQUEST_CODE_TWO_VERIFY = 0x010;
    private static final int EDIT_INPUT_OK = 0x005;
    private AssetListResponse.BalanceBean assetItemBean;
    //最大可提数量
    private String maxWithdrawValue = "";
    private String minMinerFee = "";
    private String maxMinerFee = "";
    private StepView stepView;
    private double feeRange = 0;
    private String minWithDrawAmount = "";
    private String withdrawFee;
    private double avaliableWithDrawMaxQuota;
    private TextView sendVerifyCodeTv;
    private boolean bindGA = false;
    private String mobile = "";
    private String email = "";
    private boolean isBindMobile = false;
    private boolean isBindEmail = false;
    private boolean isVerifyEmail = false;
    private TopBar topBar;
    //计算后的手续费
    private double fee;
    private TwoVerifyBean twoVerify;
    private String currentCodeId = "";
    private String requestId = "";
    private boolean isNeedTag = false;
    private CheckBox noTagCb;
    private String tag;
    //小数精度位数
    private int minPrecision=AppData.Config.DIGIT_DEFAULT_VALUE;
    private String lastAmountTxt="";
    private PointLengthFilter amountFilter;
    private AddressListResponse.AddressBean addressSelect;
    private FeeBeanResponse currentFeeBean;
    private InputView idCardInput;
    private InputView financeInput;
    private AlertDialog brokerDialog;
    private boolean isShowIdCard=false;
    private boolean isShowFinancePasswdView=false;
    private String currentTokenName="";
    private EditText addressEdt;
    private EditText addressTagEdt;
    private boolean isSetFee=false;
    private String available="";
    private TextView chainsTitle;
    private RecyclerView chainTypeRV;
    private String selectChainType="";
    private TextView addressMarkTv;
    private EditText amountEt;
    private TextWatcher textWatcherOfAmountEt;
    private TextWatcher textWatcherOfArrivalAmountEt;
    private EditText arrivalAmountEt;
    private PopWindow popWindowOfRiskyAssetsTips;
    private TextView riskyAssetsTv;

    @Override
    protected int getContentView() {
        return R.layout.activity_withdraw_coin_layout;
    }

    @Override
    protected WithdrawCoinPresenter createPresenter() {
        return new WithdrawCoinPresenter();
    }

    @Override
    protected WithdrawCoinPresenter.WithdrawCoinUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setLeftImg(R.mipmap.icon_close);
        if (intent != null) {
            assetItemBean = (AssetListResponse.BalanceBean) intent.getSerializableExtra(AppData.INTENT.KEY_ASSET);
            if (assetItemBean != null) {

//                String iconUrl = assetItemBean.getIconUrl();
//                if (!TextUtils.isEmpty(iconUrl)) {
//                    ImageView icon = viewFinder.imageView(R.id.coin_icon);
//                    Glide.with(this).load(iconUrl).into(icon);
//                }

                viewFinder.textView(R.id.asset_token_fullname).setText(assetItemBean.getTokenFullName());
                viewFinder.textView(R.id.asset_token).setText(assetItemBean.getTokenName());
                viewFinder.textView(R.id.token_avaliable_amount_title).setText(getString(R.string.string_can_withdraw)+":");
                viewFinder.textView(R.id.token_withdraw_amount_unit).setText(assetItemBean.getTokenName());
                viewFinder.textView(R.id.token_arrival_amount_unit).setText(assetItemBean.getTokenName());

//                viewFinder.textView(R.id.with_tips_a).setText(getString(R.string.string_with_tips_a,assetItemBean.getTokenName(),assetItemBean.getTokenName()));

                topBar.setTitle(assetItemBean.getTokenName() + getString(R.string.title_withdraw_coin));

                String tokenId = assetItemBean.getTokenId();
                currentTokenName = assetItemBean.getTokenName();
                if (tokenId.equalsIgnoreCase("Grin") || tokenId.equalsIgnoreCase("Beam")) {
                    viewFinder.find(R.id.withdraw_tips_a).setVisibility(View.VISIBLE);
                }

                if (tokenId.equalsIgnoreCase("ETH")) {
                    viewFinder.find(R.id.withdraw_tips_eth).setVisibility(View.VISIBLE);
                }else{
                    viewFinder.find(R.id.withdraw_tips_eth).setVisibility(View.GONE);
                }

                if (tokenId.equalsIgnoreCase("ZEC")) {
                    viewFinder.find(R.id.withdraw_tips_zec).setVisibility(View.VISIBLE);
                }else{
                    viewFinder.find(R.id.withdraw_tips_zec).setVisibility(View.GONE);
                }

            }
            initChainTypeChoice(assetItemBean.getTokenId());
        }

        riskyAssetsTv = viewFinder.textView(R.id.riskyAssets);

        addressMarkTv = viewFinder.textView(R.id.addressMark);
        stepView = viewFinder.find(R.id.stepView);
        noTagCb = viewFinder.find(R.id.no_tag);
        addressEdt =viewFinder.editText(R.id.token_withdraw_address_et);
        addressTagEdt =viewFinder.editText(R.id.withdraw_tag_et);

        ShadowDrawable.setShadow(viewFinder.find(R.id.selectTokenRela));
        ShadowDrawable.setShadow(viewFinder.find(R.id.token_withdraw_address_rela));
        ShadowDrawable.setShadow(viewFinder.find(R.id.token_withdraw_amount_rela));
        ShadowDrawable.setShadow(viewFinder.find(R.id.token_withdraw_fee_rela));
        ShadowDrawable.setShadow(viewFinder.find(R.id.withdraw_tag_et));
        ShadowDrawable.setShadow(viewFinder.find(R.id.token_arravle_amount_rela));
        amountFilter = new PointLengthFilter();

        initViewOfFinance();
        initViewOfIdCard();
        initRiskyAssetsPop();

    }

    private void initRiskyAssetsPop() {
        TextView textView = new TextView(this);
        textView.setText(getString(R.string.string_risky_assets_not_allowed_withdraw));
        textView.setPadding(PixelUtils.dp2px(12),PixelUtils.dp2px(8),PixelUtils.dp2px(12),PixelUtils.dp2px(8));
        textView.setTextColor(SkinColorUtil.getWhite(this));
        textView.setBackgroundColor(SkinColorUtil.getDark50(this));
        popWindowOfRiskyAssetsTips = new PopWindow(this, textView);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            assetItemBean = (AssetListResponse.BalanceBean) intent.getSerializableExtra(AppData.INTENT.KEY_ASSET);
            if (assetItemBean != null) {

                resetView();

                viewFinder.textView(R.id.asset_token_fullname).setText(assetItemBean.getTokenFullName());
                viewFinder.textView(R.id.asset_token).setText(assetItemBean.getTokenName());
                viewFinder.textView(R.id.token_avaliable_amount_title).setText(getString(R.string.string_can_withdraw)+":");
                viewFinder.textView(R.id.token_withdraw_amount_unit).setText(assetItemBean.getTokenName());
                viewFinder.textView(R.id.token_arrival_amount_unit).setText(assetItemBean.getTokenName());

//                viewFinder.textView(R.id.with_tips_a).setText(getString(R.string.string_with_tips_a,assetItemBean.getTokenName(),assetItemBean.getTokenName()));

                topBar.setTitle(assetItemBean.getTokenName() + getString(R.string.title_withdraw_coin));

                String tokenId = assetItemBean.getTokenId();
                currentTokenName = assetItemBean.getTokenName();
                if (tokenId.equalsIgnoreCase("Grin") || tokenId.equalsIgnoreCase("Beam")) {
                    viewFinder.find(R.id.withdraw_tips_a).setVisibility(View.VISIBLE);
                }

                if (tokenId.equalsIgnoreCase("ETH")) {
                    viewFinder.find(R.id.withdraw_tips_eth).setVisibility(View.VISIBLE);
                }else{
                    viewFinder.find(R.id.withdraw_tips_eth).setVisibility(View.GONE);
                }

                if (tokenId.equalsIgnoreCase("ZEC")) {
                    viewFinder.find(R.id.withdraw_tips_zec).setVisibility(View.VISIBLE);
                }else{
                    viewFinder.find(R.id.withdraw_tips_zec).setVisibility(View.GONE);
                }


                if (assetItemBean != null) {
                    getPresenter().getAddressListByToken(assetItemBean.getTokenId(),selectChainType);
                    refreshFeeBean();
                }

            }
            initChainTypeChoice(assetItemBean.getTokenId());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        refreshFeeBean();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (assetItemBean != null && UserInfo.isLogin()) {
            String tokenId = assetItemBean.getTokenId();
            getPresenter().getAddressListByToken(tokenId,selectChainType);
        }
    }

    /**
     * 初始化-连路类型选择
     * @param tokenId
     */
    private void initChainTypeChoice(String tokenId) {
        chainsTitle = viewFinder.textView(R.id.chainsTitle);
        chainTypeRV = viewFinder.find(R.id.chainTypeRV);
        List<io.bhex.sdk.quote.bean.ChainType> chainTypes = SymbolDataManager.GetInstance().getTokenChainTypesByTokenId(tokenId);
        if (chainTypes != null&&chainTypes.size()>0) {
            //提币默认类型设置
            boolean isSetSelected = false;
            for (ChainType chainType : chainTypes) {
                if (!isSetSelected && chainType.isAllowWithdraw()) {
                    chainType.setSelect(true);
                    isSetSelected = true;
                    selectChainType = chainType.getChainType();
                }else{
                    chainType.setSelect(false);
                }
            }
            chainsTitle.setVisibility(View.VISIBLE);
            chainTypeRV.setVisibility(View.VISIBLE);
            ChainTypeViewController.getInstance().showChainTypesGrid(this,chainTypes, chainTypeRV, 2, new ChainTypeViewController.ChainTypeSelectListener() {
                @Override
                public void onItemSelect(ChainType selectChain) {
                    //切换链路
//                    ToastUtils.showShort(selectChain.getChainType());
                    resetView();
                    selectChainType = selectChain.getChainType();
                    if (assetItemBean != null) {
                        getPresenter().getAddressListByToken(assetItemBean.getTokenId(),selectChainType);
                        refreshFeeBean();
                    }

                }
            });
        }else{
            chainsTitle.setVisibility(View.GONE);
            chainTypeRV.setVisibility(View.GONE);
        }
    }

//    /**
//     * 重置提币数据配置信息
//     */
//    private void resetView() {
//        //TODO 待处理
//
//    }

    public void showFinancePasswd(boolean isShow){
        if (isShow) {
            if (financeInput != null) {
                financeInput.setInputString("");
                financeInput.setFocusable(true);
            }
        }
        viewFinder.find(R.id.finance_passwd_view).setVisibility(isShow?View.VISIBLE:View.GONE);
        isShowFinancePasswdView = isShow;
    }

    /**
     * 单独框-资金密码
     */
    private void initViewOfFinance() {
        TopBar topBarOfFinance =  viewFinder.find(R.id.topBarOfFinancePasswd);
        topBarOfFinance.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.hideKeyboard(WithdrawCoinActivity.this);
                viewFinder.find(R.id.finance_passwd_view).setVisibility(View.GONE);
            }
        });
        financeInput = viewFinder.find(R.id.input_finance);
        viewFinder.find(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String address = viewFinder.editText(R.id.token_withdraw_address_et).getText().toString().trim();
                if (TextUtils.isEmpty(address)) {
                    ToastUtils.showShort(WithdrawCoinActivity.this, getString(R.string.string_tips_input_coin_address));
                    return;
                }

                String amount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
                if (TextUtils.isEmpty(amount)) {
                    ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_tips_input_withdraw_amount));
                    return;
                }


                String financePasswd = financeInput.getInputString();
                if (TextUtils.isEmpty(financePasswd)) {
                    ToastUtils.showLong(WithdrawCoinActivity.this, getString(R.string.input_finance_passwd));
                    return;
                }
                String tagStr = isNeedTag ? tag :"";
                String withdrawFee = calUserSelectMinerFee(address+"###"+ tagStr);
//                showFinancePasswd(false);
                //TODO 携带资金密码去提币
                String addressId ="";
                if (addressSelect != null) {
                    addressId =  addressSelect.getId();
                }
                getPresenter().requstWithdraw(true,assetItemBean.getTokenId(),selectChainType, address,addressId, amount, withdrawFee, 0, "", "", isNeedTag, tag,financePasswd);
            }
        });
    }

    public void showIdCard(boolean isShow){
        if (isShow) {
            if (idCardInput != null) {
                idCardInput.setInputString("");
                idCardInput.setFocusable(true);
            }
        }
        viewFinder.find(R.id.idcard_view).setVisibility(isShow?View.VISIBLE:View.GONE);
        isShowIdCard = isShow;
    }

    /**
     * 身份验证
     */
    private void initViewOfIdCard() {
        TopBar topBarOfIdCard =  viewFinder.find(R.id.topBarOfIdCard);
        topBarOfIdCard.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.hideKeyboard(WithdrawCoinActivity.this);
                viewFinder.find(R.id.idcard_view).setVisibility(View.GONE);
            }
        });
       idCardInput = viewFinder.find(R.id.input_idcard);
       //身份验证 继续提币
       viewFinder.find(R.id.btn_idcard_withdraw).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               String idcard = idCardInput.getInputString();
               if (TextUtils.isEmpty(idcard)) {
                   ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_hint_input_idcard,getString(R.string.app_name)));
                   return;
               }

               //TODO 去提币-携带idcard
//               showIdCard(false);
                getPresenter().verifyWithdraw(true,requestId, currentCodeId, assetItemBean.getTokenId(), "",false,idcard);

            }
        });
        //跳过身份验证-继续提币
        viewFinder.find(R.id.btn_skip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 去提币-不携带idcard
//               showIdCard(false);
                getPresenter().verifyWithdraw(true,requestId, currentCodeId, assetItemBean.getTokenId(), "",true,"");
            }
        });
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            KeyBoardUtil.hideKeyboard(this);
            if (isShowFinancePasswdView){
                showFinancePasswd(false);
                return true;
            }
            if (isShowIdCard){
                showIdCard(false);
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.selectTokenRela).setOnClickListener(this);
        viewFinder.find(R.id.withdraw_all).setOnClickListener(this);
        viewFinder.find(R.id.btn_withdraw).setOnClickListener(this);
        viewFinder.find(R.id.btn_address_history).setOnClickListener(this);
        viewFinder.find(R.id.btn_scan).setOnClickListener(this);
        viewFinder.find(R.id.riskyAssetsLinear).setOnClickListener(this);
        viewFinder.find(R.id.riskyAssetsTipsIcon).setOnClickListener(this);
        ((CheckBox) viewFinder.find(R.id.speed_switch)).setOnCheckedChangeListener(this);
        /** 提币数量监听 ****/
        amountEt = viewFinder.editText(R.id.token_withdraw_amount_et);
        amountEt.setFilters(new InputFilter[]{amountFilter});
        textWatcherOfAmountEt = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                arrivalAmountEt.removeTextChangedListener(textWatcherOfArrivalAmountEt);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setWithdrawArrivalAmount();
            }

            @Override
            public void afterTextChanged(Editable s) {
                arrivalAmountEt.addTextChangedListener(textWatcherOfArrivalAmountEt);
            }
        };
        amountEt.addTextChangedListener(textWatcherOfAmountEt);

        /** 到账数量监听 ****/
        arrivalAmountEt = viewFinder.editText(R.id.token_arrival_amount_et);
        arrivalAmountEt.setFilters(new InputFilter[]{amountFilter});
        //到账数量监听
        textWatcherOfArrivalAmountEt = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                amountEt.removeTextChangedListener(textWatcherOfAmountEt);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setWithdrawAmount();
            }

            @Override
            public void afterTextChanged(Editable s) {
                amountEt.addTextChangedListener(textWatcherOfAmountEt);
            }
        };
        arrivalAmountEt.addTextChangedListener(textWatcherOfArrivalAmountEt);

        stepView.setOnProgressListener(this);
        noTagCb.setOnCheckedChangeListener(this);
        //地址输入框监听
        addressEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mRunnable != null) {
                    mHandler.removeCallbacks(mRunnable);
                }
                //800毫秒没有输入认为输入完毕
                mHandler.postDelayed(mRunnable, 800);
            }

            @Override
            public void afterTextChanged(Editable s) {
//                String inputText = s.toString();
//                DebugLog.e("####### afterTextChanged "+inputText);
            }
        });
        //TAG输入框监听
        addressTagEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mRunnable != null) {
                    mHandler.removeCallbacks(mRunnable);
                }
                //800毫秒没有输入认为输入完毕
                mHandler.postDelayed(mRunnable, 800);
            }

            @Override
            public void afterTextChanged(Editable s) {
//                String inputText = s.toString();
//                DebugLog.e("####### afterTextChanged "+inputText);
            }
        });

    }

    /**
     * 地址输入框的延迟处理
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (EDIT_INPUT_OK == msg.what) {
               checkAddress();
            }
        }
    };

    private void checkAddress() {
        if (assetItemBean != null) {
            String address = addressEdt.getText().toString().trim();
//                DebugLog.d("#######", "输入完成: "+address );
            String tagStr = addressTagEdt.getText().toString().trim();
            checkSetAddrressMark(address,tagStr);
            if (TextUtils.isEmpty(address)) {
                //地址为空不校验
                return;
            }
            getPresenter().checkAddressIsInBlackList(false,assetItemBean.getTokenId(),selectChainType,address, tagStr);
        }
    }

    /**
     * 检查设置地址备注
     * @param address
     * @param tagStr
     */
    private void checkSetAddrressMark(String address, String tagStr) {
        AddressListResponse.AddressBean addressBean = getPresenter().getAddressList(address, tagStr, currentFeeBean);
        if (addressBean!=null){
            if (!TextUtils.isEmpty(addressBean.getRemark())) {
                addressMarkTv.setVisibility(View.VISIBLE);
                addressMarkTv.setText(addressBean.getRemark());
                return;
            }
        }

        addressMarkTv.setVisibility(View.GONE);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(EDIT_INPUT_OK);
        }
    };

    @Override
    public void showFeeInfo(FeeBeanResponse response) {
        if (response != null) {
            if (!response.isAllowWithdraw()) {
                DialogUtils.showDialogOneBtn(this, "", response.getRefuseReason(), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
                    @Override
                    public void onConfirm() {
                        WithdrawCoinActivity.this.finish();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            }
        }
        isNeedTag = response.isNeedAddressTag();
        currentFeeBean = response;
        minPrecision = response.getMinPrecision();
        amountFilter.setDecimalLength(minPrecision);
        if (response.isNeedAddressTag()) {
            viewFinder.editText(R.id.withdraw_tag_et).setEnabled(true);
            viewFinder.find(R.id.tag_linear).setVisibility(View.VISIBLE);
        }else{
            viewFinder.editText(R.id.withdraw_tag_et).setText("");
            viewFinder.editText(R.id.withdraw_tag_et).setEnabled(false);
            viewFinder.find(R.id.tag_linear).setVisibility(View.GONE);
        }
        avaliableWithDrawMaxQuota = NumberUtils.sub(response.getDayQuota(), response.getUsedQuota());
        available = response.getAvailable();
        if (!TextUtils.isEmpty(available)) {
            if (Double.valueOf(available) < avaliableWithDrawMaxQuota) {
                if(new BigDecimal(available).compareTo(new BigDecimal(avaliableWithDrawMaxQuota))==-1){
                    avaliableWithDrawMaxQuota = new BigDecimal(NumberUtils.roundFormatDown(available,AppData.Config.DIGIT_DEFAULT_VALUE)).doubleValue();
                }
            }
        }

        if (avaliableWithDrawMaxQuota < 0) {
            avaliableWithDrawMaxQuota = 0;
        }
        maxWithdrawValue = NumberUtils.roundFormatDown(avaliableWithDrawMaxQuota, AppData.Config.DIGIT_DEFAULT_VALUE);
        viewFinder.textView(R.id.token_avaliable_amount).setText(NumberUtils.roundFormatDown(available, minPrecision) + assetItemBean.getTokenName());
        minWithDrawAmount = response.getMinQuantity();
        viewFinder.editText(R.id.token_withdraw_amount_et).setHint(getString(R.string.string_hint_min_withdraw_amount, minWithDrawAmount));
        fee = calFee(response);
//        minMinerFee = ""+ calConversionMinerFee(currentFeeBean,response.getMinMinerFee());
        minMinerFee = ""+ fee;
        maxMinerFee = ""+ calConversionMinerFee(currentFeeBean,response.getMaxMinerFee());
        feeRange = NumberUtils.sub(maxMinerFee, minMinerFee);
        viewFinder.textView(R.id.stepView_minTxt).setText(NumberUtils.roundFormatDown(minMinerFee, AppData.Config.DIGIT_DEFAULT_VALUE));
        viewFinder.textView(R.id.stepView_maxTxt).setText(getString(R.string.string_stepview_max_txt_format, NumberUtils.roundFormatDown(maxMinerFee, AppData.Config.DIGIT_DEFAULT_VALUE), assetItemBean.getTokenName()));
//        viewFinder.textView(R.id.with_tips_a).setText(getString(R.string.string_withdraw_tip_a,response.getMinQuantity()));
//        viewFinder.textView(R.id.with_tips_b).setText(getString(R.string.string_withdraw_tip_b,response.getDayQuota()));
//        viewFinder.textView(R.id.withdraw_fee_tx).setText(getString(R.string.string_format_withdraw_fee,response.getFeeTokenName()));

//        viewFinder.textView(R.id.withdraw_fee).setText(minMinerFee);

        viewFinder.textView(R.id.token_withdraw_fee_unit).setText(assetItemBean.getTokenName());

        viewFinder.textView(R.id.withdraw_tips).setText(getString(R.string.string_withdraw_tips, response.getMinQuantity(), assetItemBean.getTokenName()));

        //设置风险资产
        String riskBalanceBtcValue = currentFeeBean.getRiskBalanceBtcValue();
        if (!TextUtils.isEmpty(riskBalanceBtcValue) && !riskBalanceBtcValue.equals("0")) {
            viewFinder.find(R.id.riskyAssetsLinear).setVisibility(View.VISIBLE);
            riskyAssetsTv.setText(getString(R.string.string_risky_assets)+":"+currentFeeBean.getRiskBalanceBtcValue()+" BTC");
        }else{
            viewFinder.find(R.id.riskyAssetsLinear).setVisibility(View.GONE);
        }

        String tokenType = response.getTokenType();
        if (!TextUtils.isEmpty(tokenType)) {
            if (tokenType.equals("ERC20_TOKEN")) {
                viewFinder.textView(R.id.withdraw_tips_erc_token).setVisibility(View.VISIBLE);
                viewFinder.textView(R.id.withdraw_tips_erc_token).setText(getString(R.string.string_withdraw_erc20_token_tips,assetItemBean.getTokenName()));
            }else{
                viewFinder.textView(R.id.withdraw_tips_erc_token).setVisibility(View.GONE);

            }
        }
        if (!isSetFee) {
            isSetFee = true;
            setFee(fee+"");
            //设置建议旷工费
            String suggestMinerFee = currentFeeBean.getSuggestMinerFee();
            if (!TextUtils.isEmpty(suggestMinerFee)) {
                setFee(calConversionMinerFee(currentFeeBean,currentFeeBean.getSuggestMinerFee())+"");
                String progress = NumberUtils.div(feeRange,NumberUtils.sub(calConversionMinerFee(currentFeeBean,suggestMinerFee),fee))+"";
                stepView.setStepProgress(Float.valueOf(progress));
            }

            checkAddress();
            setWithdrawArrivalAmount();
        }
    }

    /**
     * 重置提币数据配置信息
     */
    private void resetView() {
        isSetFee = false;
        selectChainType = "";
        addressEdt.setText("");
        viewFinder.editText(R.id.token_withdraw_amount_et).setText("");
        viewFinder.editText(R.id.token_withdraw_amount_et).setHint("");
        viewFinder.textView(R.id.stepView_minTxt).setText("");
        viewFinder.textView(R.id.stepView_maxTxt).setText("");
        viewFinder.textView(R.id.token_withdraw_fee_unit).setText("");
        viewFinder.textView(R.id.withdraw_tips).setText("");
        viewFinder.textView(R.id.token_withdraw_fee_edit).setText("");
        viewFinder.editText(R.id.token_arrival_amount_et).setText("");

        // Tag
        viewFinder.editText(R.id.withdraw_tag_et).setText("");
        viewFinder.editText(R.id.withdraw_tag_et).setEnabled(false);
        viewFinder.find(R.id.tag_linear).setVisibility(View.GONE);

        getPresenter().resetData();

    }


    /**
     * 显示正常手续费
     */
    private void showNormalFee(boolean isResetFee) {
        viewFinder.find(R.id.withdraw_progress_rela).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.stepView).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.fee_range_linear).setVisibility(View.VISIBLE);
        if (isResetFee) {
//            stepView.setStepProgress(stepView.getStepProgress());
            double totalFeeD = NumberUtils.add(NumberUtils.mul(feeRange,stepView.getStepProgress()),fee);
            setFee(totalFeeD+"");
            setWithdrawArrivalAmount();
        }
    }

    /**
     * 设置手续费
     * @param fee
     */
    public void setFee(String fee) {
        String totalFee = NumberUtils.roundFormatUp(fee,minPrecision);
        viewFinder.textView(R.id.token_withdraw_fee_edit).setText(totalFee);
    }

    /**
     * 计算手续费
     *
     * @param feeBean
     */
    private double calFee(FeeBeanResponse feeBean) {
        double fee = 0d;
        if (assetItemBean != null && feeBean != null) {
            // arrivalAccountAmount 到账金额
            if (assetItemBean.getTokenId().equals(feeBean.getMinerFeeTokenId())) {
                fee = NumberUtils.add(feeBean.getFee(), feeBean.getMinMinerFee());
            } else {
                if (assetItemBean.getTokenId().equals(feeBean.getFeeTokenId())) {
                    fee = NumberUtils.add(feeBean.getFee(), String.valueOf(NumberUtils.mul(feeBean.getMinMinerFee(), feeBean.getConvertRate())));
                } else {
                    fee = NumberUtils.add(feeBean.getConvertFee(), String.valueOf(NumberUtils.mul(feeBean.getMinMinerFee(), feeBean.getConvertRate())));
                }
            }
        }
        return fee;

    }

    /**
     * 计算转换旷工费
     *
     * @param feeBean
     * @param minerFee
     */
    private double calConversionMinerFee(FeeBeanResponse feeBean,String minerFee) {
        double fee = 0d;
        if (assetItemBean != null && feeBean != null && !TextUtils.isEmpty(minerFee)) {
            // arrivalAccountAmount 到账金额
            if (assetItemBean.getTokenId().equals(feeBean.getMinerFeeTokenId())) {
                fee = NumberUtils.add(feeBean.getFee(), minerFee);
            } else {
                if (assetItemBean.getTokenId().equals(feeBean.getFeeTokenId())) {
                    fee = NumberUtils.add(feeBean.getFee(), String.valueOf(NumberUtils.mul(minerFee, feeBean.getConvertRate())));
                } else {
                    fee = NumberUtils.add(feeBean.getConvertFee(), String.valueOf(NumberUtils.mul(minerFee, feeBean.getConvertRate())));
                }
            }
        }
        return fee;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.selectTokenRela:
                IntentUtils.goTokenList(this,false);
                break;
            case R.id.withdraw_all:
                //全部提币
                viewFinder.editText(R.id.token_withdraw_amount_et).setText(NumberUtils.roundFormatDown(maxWithdrawValue,minPrecision));
                break;
            case R.id.riskyAssetsTipsIcon:
                //风险资产提示
                popWindowOfRiskyAssetsTips.showAsDropDown(viewFinder.find(R.id.riskyAssetsTipsIcon), 0,0,Gravity.TOP);
                break;
            case R.id.riskyAssetsLinear:
                //风险资产
                if (currentFeeBean != null) {
                    IntentUtils.goRiskyAssets(this,currentFeeBean);
                }
                break;
            case R.id.btn_address_history:
                if (assetItemBean != null&&currentFeeBean!=null) {
                    IntentUtils.goCoinAddressList(this, selectChainType,assetItemBean.getTokenId(), assetItemBean.getTokenName(), assetItemBean.getIconUrl(), assetItemBean.getTokenFullName(), REQUEST_CODE_ADDRESS,currentFeeBean.isNeedAddressTag());
                }else{
                    ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_wait_retry));
                    refreshFeeBean();
                }
                break;
            case R.id.btn_scan:
                IntentUtils.goScan(this, REQUEST_CODE_SCAN);
                break;
            case R.id.btn_withdraw:
                String address = viewFinder.editText(R.id.token_withdraw_address_et).getText().toString().trim();
                if (TextUtils.isEmpty(address)) {
                    ToastUtils.showShort(this,getString(R.string.string_tips_input_coin_address));
                    return;
                }
                String amount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
                if (TextUtils.isEmpty(amount)) {
                    ToastUtils.showShort(this,getString(R.string.string_tips_input_withdraw_amount));
                    return;
                }
                if (!TextUtils.isEmpty(minWithDrawAmount) && new BigDecimal(amount).compareTo(new BigDecimal(minWithDrawAmount)) < 0) {
                    ToastUtils.showShort(this, getString(R.string.string_hint_min_withdraw_amount, minWithDrawAmount));
                    return;
                }
//                if (!TextUtils.isEmpty(minWithDrawAmount)&&Double.valueOf(amount) < Double.valueOf(minWithDrawAmount)) {
//                    ToastUtils.showShort(getString(R.string.string_hint_min_withdraw_amount, minWithDrawAmount));
//                    return;
//                }

//                withdrawFee = viewFinder.textView(R.id.withdraw_fee).getText().toString();
                withdrawFee = viewFinder.textView(R.id.token_withdraw_fee_edit).getText().toString();
                //手续费为空放行
                if (!TextUtils.isEmpty(withdrawFee) && new BigDecimal(amount).compareTo(new BigDecimal(withdrawFee)) <= 0) {
                    ToastUtils.showShort(this,getString(R.string.string_hint_min_withdraw_amount_need_over_fee, minWithDrawAmount));
                    return;
                }

                if (currentFeeBean == null) {
                    ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_wait_retry));
                    refreshFeeBean();
                    return;
                }
                if (currentFeeBean.isNeedAddressTag()&&!noTagCb.isChecked()) {
                    tag = viewFinder.editText(R.id.withdraw_tag_et).getText().toString();
                    if (TextUtils.isEmpty(tag)) {
                        ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_input_tag_hint));
                        return;
                    }
                }

//                if (!TextUtils.isEmpty(maxWithdrawValue) && new BigDecimal(amount).compareTo(new BigDecimal(maxWithdrawValue)) > 0) {
//                    ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_hint_over_max_withdraw_amount, maxWithdrawValue));
//                    return;
//                }

                if (!TextUtils.isEmpty(available) && new BigDecimal(amount).compareTo(new BigDecimal(available)) > 0) {
                    ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_hint_over_max_withdraw_amount, available));
                    return;
                }

                if (currentFeeBean != null) {

                    /**
                     * 根据用户绑定新系统，提示用户是否可以提币
                     */
                    KeyBoardUtil.closeKeybord(viewFinder.editText(R.id.token_withdraw_amount_et),this);
                    getPresenter().checkAddressIsInBlackList(true, assetItemBean.getTokenId(),selectChainType,address,tag);
                }else{
                    ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_wait_retry));
                    refreshFeeBean();
                    return;
                }

                break;
        }
    }

    private HashMap<String,AddressCheckResponse> checkAddressMap = new HashMap<String,AddressCheckResponse>();

    /**
     * 显示校验地址
     * @param isGoWithDraw 是否是去提币
     * @param response
     */
    @Override
    public void showCheckAddress(boolean isGoWithDraw,AddressCheckResponse response) {
        if (response != null) {
            String address = TextUtils.isEmpty(response.getAddress())?"":response.getAddress();
            String addressExt = TextUtils.isEmpty(response.getAddressExt())?"":response.getAddressExt();
            if (!TextUtils.isEmpty(address)) {
                checkAddressMap.put(address+"###"+addressExt,response);
            }

            if (isGoWithDraw) {//去提币
                if (response.isIsInBlackList()) {
                    DialogUtils.showDialog(this, "", getString(R.string.string_tips_risk_address), getString(R.string.string_continue_withdraw), getString(R.string.string_change_address), true, new DialogUtils.OnButtonEventListener() {
                        @Override
                        public void onConfirm() {
                            getPresenter().getUserInfo();
                        }

                        @Override
                        public void onCancel() {
                            viewFinder.editText(R.id.token_withdraw_address_et).setText("");
                            viewFinder.editText(R.id.withdraw_tag_et).setText("");
                        }
                    });
                }else{
                    getPresenter().getUserInfo();
                }
            }else{
                //非去提币-处理内部地址手续费展示
                handleInternalAddressFeeShow(response);
            }
        }
    }


    /**
     * 处理手续费显示问题
     * @param response
     */
    private void handleInternalAddressFeeShow(AddressCheckResponse response) {
        if (response != null) {
            boolean isInnerAddress = response.isIsInnerAddress();
            if (isInnerAddress) {
                viewFinder.find(R.id.withdraw_progress_rela).setVisibility(View.GONE);
                viewFinder.find(R.id.stepView).setVisibility(View.GONE);
                viewFinder.find(R.id.fee_range_linear).setVisibility(View.GONE);
                //内部地址 显示手续费为零
//                stepView.setStepProgress(0f);
                setFee("0.00000000");
                if (currentFeeBean != null) {
                    if (currentFeeBean.isInternalWithdrawHasFee()) {
                        String internalWithdrawFee = currentFeeBean.getInternalWithdrawFee();
                        if (!TextUtils.isEmpty(internalWithdrawFee)) {
                            setFee(internalWithdrawFee);
                        }
                    }
                }
                setWithdrawArrivalAmount();
            }else{
                //非内部地址显示正常手续费
                if (currentFeeBean != null) {
                    showNormalFee(true);
                }
            }
        }
    }

    private void refreshFeeBean() {
        if (assetItemBean != null) {
            if (!NetWorkStatus.isConnected(this)) {
                ToastUtils.showShort(this,getResources().getString(R.string.hint_network_not_connect));
                return;
            }
            getPresenter().getQuotaInfo(assetItemBean.getTokenId(),selectChainType);
        }
    }

    /**
     * 去提币
     * @param currentFeeBean
     */
    private void goWithDraw(FeeBeanResponse currentFeeBean) {


    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.speed_switch:
                if (isChecked) {
                    viewFinder.find(R.id.stepView).setVisibility(View.VISIBLE);
                    viewFinder.find(R.id.fee_range_linear).setVisibility(View.VISIBLE);
                } else {
                    stepView.setStepProgress(0);
                    viewFinder.find(R.id.stepView).setVisibility(View.GONE);
                    viewFinder.find(R.id.fee_range_linear).setVisibility(View.GONE);
//            viewFinder.textView(R.id.withdraw_fee).setText(minMinerFee);
                    setFee(minMinerFee);
                }
                break;
            case R.id.no_tag:
                isNeedTag = !isChecked;
                viewFinder.editText(R.id.withdraw_tag_et).setEnabled(isNeedTag);
                viewFinder.editText(R.id.withdraw_tag_et).setVisibility(isNeedTag?View.VISIBLE:View.GONE);
                if (isChecked) {
                    viewFinder.editText(R.id.withdraw_tag_et).setText("");
                }
                break;
        }
    }

    /**
     * 设置到账数量
     */
    private void setWithdrawArrivalAmount() {
        String withDrawAmount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
        if (!TextUtils.isEmpty(withDrawAmount)) {
            withDrawAmount = NumberUtils.roundFormatDown(withDrawAmount, minPrecision);
//            viewFinder.editText(R.id.token_withdraw_amount_et).setText(s);
        }else{
            arrivalAmountEt.setText("");
            return;
        }

        if (assetItemBean != null) {
            String tokenName = assetItemBean.getTokenName();
            if (TextUtils.isEmpty(tokenName)) {
                tokenName = "";
            }
            String currentFee = viewFinder.textView(R.id.token_withdraw_fee_edit).getText().toString();
            //显示的默认到账不可能为零，做本地特殊处理一下
            double result = NumberUtils.sub(withDrawAmount,currentFee);
            if (result<0){
                result = 0d;
                arrivalAmountEt.setText("");
            }else{
                String toHandAmount = NumberUtils.roundFormatDown(result, minPrecision);
                arrivalAmountEt.setText(toHandAmount);
            }
        }
    }

    /**
     * 设置提币数量
     */
    private void setWithdrawAmount() {
        String arrivalAmount = arrivalAmountEt.getText().toString();
        if (TextUtils.isEmpty(arrivalAmount)) {
            amountEt.setText("");
            return;
        }

        if (assetItemBean != null) {
            String tokenName = assetItemBean.getTokenName();
            if (TextUtils.isEmpty(tokenName)) {
                tokenName = "";
            }
            String currentFee = viewFinder.textView(R.id.token_withdraw_fee_edit).getText().toString();
            //显示的默认到账不可能为零，做本地特殊处理一下
            double result = NumberUtils.add(arrivalAmount,currentFee);
            if (result<0){
                result = 0d;
                amountEt.setText("");
            }else{
                String withdrawAmount = NumberUtils.roundFormatUp(result, minPrecision);
                amountEt.setText(withdrawAmount);
            }
        }
    }

    @Override
    public void onStepViewProgress(float progress) {
        double totalFeeD = NumberUtils.add(NumberUtils.mul(feeRange,progress),fee);
        String totalFee = NumberUtils.roundFormatDown(totalFeeD,AppData.Config.DIGIT_DEFAULT_VALUE);
        setFee(totalFee);
        setWithdrawArrivalAmount();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String result = data.getStringExtra("result");
                if (!TextUtils.isEmpty(result)) {
                    viewFinder.editText(R.id.token_withdraw_address_et).setText(result);
                }
            }
        } else if (requestCode == REQUEST_CODE_ADDRESS && resultCode == RESULT_OK) {
            if (data != null) {
                addressSelect = (AddressListResponse.AddressBean) data.getSerializableExtra("address");
                if (addressSelect != null) {
                    viewFinder.editText(R.id.token_withdraw_address_et).setText(addressSelect.getAddress());
                    String remark = addressSelect.getRemark();
                    addressMarkTv.setVisibility(TextUtils.isEmpty(remark)?View.GONE:View.VISIBLE);
                    addressMarkTv.setText(remark);
                    if(!TextUtils.isEmpty(addressSelect.getAddressExt())){
                        noTagCb.setChecked(false);
                        viewFinder.editText(R.id.withdraw_tag_et).setText(addressSelect.getAddressExt());
                    }else{
                        noTagCb.setChecked(true);
                        viewFinder.editText(R.id.withdraw_tag_et).setText("");
                    }
                }
            }
        } else if (requestCode == REQUEST_CODE_TWO_VERIFY && resultCode == RESULT_OK) {
            //二次验证成功，下一步，发起请求提币
            if (data != null) {
                String address = viewFinder.editText(R.id.token_withdraw_address_et).getText().toString();
                if (TextUtils.isEmpty(address)) {
                    ToastUtils.showShort(this, getString(R.string.string_tips_input_coin_address));
                    return;
                }
                String amount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
                if (TextUtils.isEmpty(amount)) {
                    ToastUtils.showShort(this,getString(R.string.string_tips_input_withdraw_amount));
                    return;
                }
                String tagStr = isNeedTag ? tag :"";
                String withdrawFee = calUserSelectMinerFee(address+"###"+tagStr);
                twoVerify = (TwoVerifyBean) data.getSerializableExtra("twoVerify");
                getPresenter().requstWithdraw(false,assetItemBean.getTokenId(),selectChainType, address,"", amount, withdrawFee, twoVerify.getAuth_type(), twoVerify.getOrder_id(), twoVerify.getVerify_code(), isNeedTag, tag,twoVerify.getTradePwd());
            }
        }
    }

    /**
     * 计算用户选择的旷工费
     * @param checkAddressKey
     */
    private String calUserSelectMinerFee(String checkAddressKey) {
        AddressCheckResponse addressCheckResponse = checkAddressMap.get(checkAddressKey);
        if (addressCheckResponse != null) {
            if (addressCheckResponse.isIsInnerAddress()) {
                //内部地址旷工费直接为零
                return "0.0";
            }
        }

        String minerFee ="";
        if (currentFeeBean != null) {
            String minMinerFee = currentFeeBean.getMinMinerFee();
            String maxMinerFee = currentFeeBean.getMaxMinerFee();
            float stepProgress = stepView.getStepProgress();
            double addMinerFee = NumberUtils.mul(stepProgress, NumberUtils.sub(maxMinerFee, minMinerFee));
            minerFee = NumberUtils.roundFormatDown(NumberUtils.add(minMinerFee, addMinerFee+""),AppData.Config.DIGIT_DEFAULT_VALUE);
        }
        return minerFee;
    }

    @Override
    public void requestUserInfoSuccess(final UserInfoBean userInfo) {
        if (userInfo != null) {
            //提示KYC
            int verifyStatus = userInfo.getVerifyStatus();
            boolean isKYC = true;
            String toastStr = "";
            if (verifyStatus==0||verifyStatus==3) {
                isKYC = false;
                toastStr = getString(R.string.string_tips_certification);

//                checkNeedKyc(false,verifyStatus,getString(R.string.string_tips_certification));
//                DialogUtils.showDialog(WithdrawCoinActivity.this, "", getString(R.string.string_tips_certification), getString(R.string.string_certification),getString(R.string.string_cancel), true, new DialogUtils.OnButtonEventListener() {
//                    @Override
//                    public void onConfirm() {
//                        IntentUtils.goIdentityAuth(WithdrawCoinActivity.this);
//                    }
//
//                    @Override
//                    public void onCancel() {
//
//                    }
//                });
//                return;
            }else if(verifyStatus==1){
                isKYC = false;
                toastStr = getString(R.string.string_kyc_checking_waiting);

//                checkNeedKyc(false, verifyStatus, getString(R.string.string_kyc_checking_waiting));
//                return;
            }

            String address = viewFinder.editText(R.id.token_withdraw_address_et).getText().toString();
            if (TextUtils.isEmpty(address)) {
                ToastUtils.showShort(this,getString(R.string.string_tips_input_coin_address));
                return;
            }

            String needKycQuantity = currentFeeBean.getNeedKycQuantity();
            String amount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
            if (TextUtils.isEmpty(amount)) {
                ToastUtils.showShort(this,getString(R.string.string_tips_input_withdraw_amount));
                return;
            }

            tag = viewFinder.editText(R.id.withdraw_tag_et).getText().toString();
            if (currentFeeBean == null) {
                ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_wait_retry));
                refreshFeeBean();
                return;
            }
            if (currentFeeBean.isNeedAddressTag()&&!noTagCb.isChecked()) {
                if (TextUtils.isEmpty(tag)) {
                    ToastUtils.showShort(this,getString(R.string.string_input_tag_hint));
                    return;
                }
            }

           if(checkNeedKyc(isKYC, verifyStatus, toastStr,amount,needKycQuantity)){
               checkNeed2FA(amount,address,tag);
           }



//            VerifyUtil.is2FA(this, userInfo, new VerifyUtil.VerifyListener() {
//                @Override
//                public void on2FAVerify(boolean isVerify2FA) {
//                    if (!isVerify2FA) {
//                        //没有二次绑定认证
//                        return;
//                    }else{
//                        int verifyStatus = userInfo.getVerifyStatus();
//                        if (verifyStatus==0||verifyStatus==3) {
//                            DialogUtils.showDialog(WithdrawCoinActivity.this, "", getString(R.string.string_tips_certification), getString(R.string.string_certification),getString(R.string.string_cancel), true, new DialogUtils.OnButtonEventListener() {
//                                @Override
//                                public void onConfirm() {
//                                    IntentUtils.goIdentityAuth(WithdrawCoinActivity.this);
//                                }
//
//                                @Override
//                                public void onCancel() {
//
//                                }
//                            });
//                            return;
//                        }else if(verifyStatus==1){
//                            ToastUtils.showLong(WithdrawCoinActivity.this,getString(R.string.string_kyc_checking_waiting));
//                            return;
//                        }
//                        bindGA = userInfo.isBindGA();
//                        mobile = userInfo.getMobile();
//                        email = userInfo.getEmail();
//                        isBindMobile = !TextUtils.isEmpty(mobile)&&userInfo.getRegisterType()!=1;
//                        isBindEmail = !TextUtils.isEmpty(email)&&userInfo.getRegisterType()!=2;
//                        //去二次验证
//                        IntentUtils.goTwoVerify(WithdrawCoinActivity.this, REQUEST_CODE_TWO_VERIFY, "from_withdraw", "", "14", bindGA, isBindMobile, isBindEmail, isVerifyEmail);
//                    }
//                }
//            });

        }
    }

    /**
     * kyc本地校验中
     * @param verifyStatus
     * @param toast
     * @param amount
     * @param needKycQuantity
     */
    private boolean checkNeedKyc(boolean isKyc, int verifyStatus, String toast, String amount, String needKycQuantity) {
        if (currentFeeBean!=null){
            if (!isKyc&&currentFeeBean.isNeedKycCheck()&& NumberUtils.sub(amount,needKycQuantity)>0) {
                //本地数量判断-需要KYC
                ToastUtils.showLong(WithdrawCoinActivity.this,toast);
                if (verifyStatus==0||verifyStatus==3) {
                    //未实名或者审核失败了
                    IntentUtils.goIdentityAuth(this);
                }
                return false;
            }else{
                return true;
            }

        }else{
            refreshFeeBean();
            return false;
        }
    }

    /**
     * 检查是否需要2FA
     * @param amount
     * @param address
     */
    private void checkNeed2FA(String amount, String address,String tag) {

        if (getPresenter().isAddressList(address,tag,currentFeeBean)) {
            //地址列表的地址，不需要2FA认证
            addressSelect = getPresenter().getAddressList(address,tag,currentFeeBean);
            showFinancePasswd(true);
//
        }else{
            //非地址列表的地址需要2FA校验
            //2FA是否开启
            if (VerifyUtil.is2FA(this,UserInfo.getUserInfo())) {
                //已认证-2FA
                UserInfoBean userInfo = UserInfo.getUserInfo();
                bindGA = userInfo.isBindGA();
                mobile = userInfo.getMobile();
                email = userInfo.getEmail();
                isBindMobile = !TextUtils.isEmpty(mobile)&&userInfo.getRegisterType()!=1;
                isBindEmail = !TextUtils.isEmpty(email)&&userInfo.getRegisterType()!=2;
                //去二次验证
                IntentUtils.goTwoVerify(WithdrawCoinActivity.this, REQUEST_CODE_TWO_VERIFY, "from_withdraw", "", "14", bindGA, isBindMobile, isBindEmail, isVerifyEmail);
            }else{
                //没有认证过-2FA
                ToastUtils.showLong(WithdrawCoinActivity.this,this.getResources().getString(R.string.string_2fa_alert_title));
                return;
            }
        }
    }

    private boolean isNeed2Fa(String address, String tag) {
        String addressOfSelect="";
        String addressTagOfSelect = "";
        String mTag = "";
        if (!TextUtils.isEmpty(tag)) {
            mTag = tag;
        }else{
            mTag="";
        }

        boolean isNeed2Fa = true;
        if (addressSelect != null) {
            if (!TextUtils.isEmpty(addressSelect.getAddress())) {
                addressOfSelect = addressSelect.getAddress();
            }
            if (!TextUtils.isEmpty(addressSelect.getAddressExt())) {
                addressTagOfSelect = addressSelect.getAddressExt();
            }
            if (currentFeeBean.isNeedAddressTag()){
//                if (!noTagCb.isChecked()) {
                isNeed2Fa = !(address.equals(addressOfSelect)&&mTag.equals(addressTagOfSelect));
//                }else{
//                    isNeed2Fa = !(address.equals(addressOfSelect));
//                }
            }else{
                isNeed2Fa = !(address.equals(addressOfSelect));
            }
        }else{
            isNeed2Fa = true;
        }
        return isNeed2Fa;
    }


    /**
     * 平台验证码
     */
    public void showBrokeVerify(String requestIdStr, String codeOrderId) {
        requestId = requestIdStr;
        currentCodeId = codeOrderId;
        UserInfoBean userInfo = UserInfo.getUserInfo();
        int registerType = userInfo.getRegisterType();
        String msg;
        if (registerType == 1) {//手机注册，邮箱验证
            msg = getString(R.string.string_verify_mobile) +" "+ userInfo.getMobile();
        } else {
            msg = getString(R.string.string_verify_email) +" "+ userInfo.getEmail();
        }
        if (brokerDialog != null&&brokerDialog.isShowing()) {
            brokerDialog.dismiss();
        }
        brokerDialog = DialogUtils.showVerifyDialog(this, getString(R.string.string_asset_custody_verification), msg, getString(R.string.string_sure), true, new DialogUtils.OnVerifyEditEventListener() {
            @Override
            public void onConfirm(Button okBtn, String editContent,TextView getVerifyView) {
                if (!TextUtils.isEmpty(editContent)) {
                    KeyBoardUtil.closeKeybord(getVerifyView,WithdrawCoinActivity.this);
                    getPresenter().verifyWithdraw(false,requestId, currentCodeId, assetItemBean.getTokenId(), editContent,true,"");
                }
            }

            @Override
            public void sendVerify(TextView btnVerify, boolean isAutoSend) {

                if (!isAutoSend) {
                    //重新发送提币请求
                    String address = viewFinder.editText(R.id.token_withdraw_address_et).getText().toString();
                    if (TextUtils.isEmpty(address)) {
                        ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_tips_input_coin_address));
                        return;
                    }
                    String amount = viewFinder.editText(R.id.token_withdraw_amount_et).getText().toString();
                    if (TextUtils.isEmpty(amount)) {
                        ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_tips_input_withdraw_amount));
                        return;
                    }
                    if (!TextUtils.isEmpty(requestId)) {
                        getPresenter().requstBrokerVerifyCode(requestId);
                    } else {
                        ToastUtils.showShort(WithdrawCoinActivity.this,getString(R.string.string_retry_withdraw_request));
                    }
                } else {
                    sendVerifyCodeTv = btnVerify;
                    setAuthTvStatus(false);
                    timer.start();
                }
            }

            @Override
            public void onCancel() {

            }
        });
    }


    @Override
    public void requestVerifyCodeSuccess(String codeOrderId) {
        currentCodeId = codeOrderId;
        setAuthTvStatus(false);
        timer.start();
    }

    @Override
    public void showWithdrawSuccess() {
        KeyBoardUtil.closeKeybord(viewFinder.editText(R.id.token_withdraw_amount_et),this);
        viewFinder.editText(R.id.token_withdraw_address_et).setText("");
        viewFinder.editText(R.id.token_withdraw_amount_et).setText("");
        viewFinder.editText(R.id.token_arrival_amount_et).setText("");
        viewFinder.textView(R.id.withdraw_tag_et).setText("");
        refreshFeeBean();
    }

    @Override
    public void showWithDrawFirst(WithDrawRequstBean response) {
        if (response.isNeedCheckIdCardNo()) {

            needCheckIdCardNo(response.getRequestId(),response.getCodeOrderId());
        }else{
            showBrokeVerify(response.getRequestId(),response.getCodeOrderId());
        }

    }

    @Override
    public void showWithDrawSecond(WithDrawVerifyBean response) {
        if (brokerDialog != null&&brokerDialog.isShowing()) {
            brokerDialog.dismiss();
        }
        if (response.isProcessIsEnd()) {
            //提币结束
            if (response.isSuccess()) {

                ToastUtils.showShort(this, getString(R.string.string_withdraw_success));
                String address = addressEdt.getText().toString().trim();
                String tag = addressTagEdt.getText().toString().trim();
                String fee = viewFinder.textView(R.id.token_withdraw_fee_edit).getText().toString();
                String feeUnit = viewFinder.textView(R.id.token_withdraw_fee_unit).getText().toString();
                String withDrawAmount = amountEt.getText().toString();
                String arrivalAmount = arrivalAmountEt.getText().toString();

                showWithdrawSuccess();
                IntentUtils.goWithDrawResult(this,assetItemBean,withDrawAmount,arrivalAmount,address,tag,fee,feeUnit);
            }else{
                ToastUtils.showShort(this,getString(R.string.string_withdraw_failed));
            }
        }else{
            //提币未结束
            if (response.isNeedCheckIdCardNo()) {
                if (!isShowIdCard) {
                    needCheckIdCardNo(requestId,response.getCodeOrderId());
                }
            }else{
                showBrokeVerify(requestId,response.getCodeOrderId());
            }
        }
    }

    /**
     * 需要校验身份信息
     * @param requestIdStr
     * @param codeOrderId
     */
    private void needCheckIdCardNo(String requestIdStr, String codeOrderId) {
        requestId = requestIdStr;
        currentCodeId = codeOrderId;
        showIdCard(true);
    }


    /**
     * 倒计时
     */
    private CountDownTimer timer = new CountDownTimer(AppData.DOWN_TIME_CODE, AppData.DOWN_TIME_INTERVAL_CODE) {
        @Override
        public void onTick(long millisUntilFinished) {
            setAuthTv((millisUntilFinished / 1000)
                    + getResources().getString(
                    R.string.after_second));
        }

        @Override
        public void onFinish() {
            setAuthTvStatus(true);
            setAuthTv(getResources().getString(
                    R.string.string_get_auth_code));
        }
    };


    public void setAuthTv(String s) {
        sendVerifyCodeTv.setText(s);
    }

    public void setAuthTvStatus(boolean b) {
        sendVerifyCodeTv.setEnabled(b);
        sendVerifyCodeTv.setTextColor(b ? getResources().getColor(R.color.blue) : SkinColorUtil.getDark50(this));
    }
}
